package com.gmzg.gmzgnews.live.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.gmzg.gmzgnews.R;
import com.gmzg.gmzgnews.live.model.LiveModel;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by EdwardGu on 2016/10/31.
 */

public class LiveFragmentAdapter extends RecyclerView.Adapter {
    private Context mContext;
    private List<LiveModel.Data.DataBean> mList;
    private View mHeadView;
    private boolean mAccess2Net;

    private final static int TYPE_HEADVIEW = 100;
    private final static int TYPE_ITEM = 101;
    private final static int TYPE_PROGRESS = 102;
    private boolean isLoading = false;
    private OnLoadMoreListener mOnLoadMoreListener;
    private static Object picassoImgTag = "PicassoTag";

    public LiveFragmentAdapter(Context context, List<LiveModel.Data.DataBean> list, RecyclerView recyclerView) {
        mContext = context;
        mList = list;
        init(recyclerView);
    }

    private void init(RecyclerView recyclerView) {
        //mRecyclerView添加滑动事件监听
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int totalItemCount = linearLayoutManager.getItemCount();
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                if (!isLoading && dy > 0 && lastVisibleItemPosition >= totalItemCount - 1) {
                    //此时是加载更多状态
                    if (mOnLoadMoreListener != null) {
                        mOnLoadMoreListener.onLoadMore();
                    }
//                    isLoading = true;
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Log.d("ddddddddd", "onScrollStateChanged: idle");
                    Picasso.with(mContext).resumeTag(picassoImgTag);
                } else {
                    Log.d("ddddddddd", "onScrollStateChanged: flying");
                    Picasso.with(mContext).pauseTag(picassoImgTag);
                }
            }
        });

    }

    public interface OnLoadMoreListener {
        void onLoadMore();
    }

    public void setOnLoadMoreListener(OnLoadMoreListener listener) {
        this.mOnLoadMoreListener = listener;
    }

    @Override
    public int getItemViewType(int position) {
        int ret = 0;
        if (mHeadView != null) {
            if (position == getItemCount() - 1) {
                ret = TYPE_PROGRESS;
            } else if (position == 0) {
                ret = TYPE_HEADVIEW;
            } else {
                ret = TYPE_ITEM;
            }
        } else {
            if (position == getItemCount() - 1) {
                ret = TYPE_PROGRESS;
            } else {
                ret = TYPE_ITEM;
            }
        }

        return ret;
    }

    public void addHeadView(View headView) {
        mHeadView = headView;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = null;
        RecyclerView.ViewHolder ret = null;
        LayoutInflater inflater = LayoutInflater.from(mContext);

        switch (viewType) {
            case TYPE_ITEM:
                itemView =
                        inflater.inflate(R.layout.item_live_hot, parent, false);
                ret = new LiveViewHolder(itemView);
                break;
            case TYPE_HEADVIEW:
                HeadViewHolder headViewHolder = new HeadViewHolder(mHeadView);
                ret = headViewHolder;
                break;
            case TYPE_PROGRESS:
                View progressView = LayoutInflater.from(mContext).inflate(R.layout.live_hot_progress_item, parent, false);
                ProgressViewHolder progressViewHolder = new ProgressViewHolder(progressView);
                ret = progressViewHolder;
                break;
            default:
                itemView =
                        inflater.inflate(R.layout.item_live_simple, parent, false);
                ret = new SimplerViewHolder(itemView);
                break;
        }
        return ret;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        LiveModel.Data.DataBean liveDataData = mList.get(position);
        if (holder instanceof SimplerViewHolder) {
            SimplerViewHolder simplerViewHolder = (SimplerViewHolder) holder;
            simplerViewHolder.bindView(liveDataData);
        }
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    private static class SimplerViewHolder extends RecyclerView.ViewHolder {
        /**
         * 通用的View缓存功能
         */
        private SparseArrayCompat<View> mViews;
//        private TextView textView;

        SimplerViewHolder(View itemView) {
            super(itemView);
            mViews = new SparseArrayCompat<>();
        }


        View getChildView(int rid) {
            View ret;
            ret = mViews.get(rid);
            if (ret == null) {
                ret = itemView.findViewById(rid);
                if (ret != null) {
                    mViews.put(rid, ret);
                }
            }
            return ret;
        }

        /**
         * @param dataData
         */
        void bindView(LiveModel.Data.DataBean dataData) {
            TextView txt = (TextView) getChildView(R.id.item_live_text);
            txt.setText("" + dataData.getType());
        }

        /**
         * 利用反射，获取视图
         *
         * @param name
         * @return
         */
        View getChildView(String name) {
            View ret = null;
            if (name != null) {
                Class aClass = R.id.class;
                int id = 0;
                try {
                    Field field = aClass.getDeclaredField(name);
                    field.setAccessible(true);
                    id = field.getInt(aClass);//获取类成员的数值
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (id != 0) {
                    ret = getChildView(id);
                }
            }

            return ret;
        }


    }

    private static class LiveViewHolder extends SimplerViewHolder implements View.OnClickListener {

        LiveViewHolder(View itemView) {
            super(itemView);
            View view = getChildView(R.id.item_live_hot_img);
            //设置点击事件
            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Object tag = v.getTag();
            if (tag != null) {
                if (tag instanceof LiveModel.Data.DataBean.GroupBean) {
                    LiveModel.Data.DataBean.GroupBean dataData = (LiveModel.Data.DataBean.GroupBean) tag;
//                    Toast.makeText(v.getContext(), "点击"+dataData.getTitle(), Toast.LENGTH_SHORT).show();
                    //EventBus 传递对象给 当前Fragment ，由Fragment来跳转到详情
                    EventBus.getDefault().post(dataData);
                }
            }
        }

        @Override
        void bindView(LiveModel.Data.DataBean dataData) {
            ImageView hotItemCover = (ImageView) getChildView(R.id.item_live_hot_img);
            TextView titleText = (TextView) getChildView(R.id.item_live_hot_txt);
            //找cover的数据地址
            LiveModel.Data.DataBean.GroupBean group = dataData.getGroup();
            List<LiveModel.Data.DataBean.GroupBean.LargeCoverBean.UrlListBean> cover;
            LiveModel.Data.DataBean.GroupBean.LargeCoverBean.UrlListBean bean;
            try {
                cover = group.getLarge_cover().getUrl_list();
                bean = cover.get(0);
                String coverUrl = bean.getUrl();
                if (coverUrl != null) {
                    //显示图片
                    Context context = hotItemCover.getContext();
                    Picasso.with(context)
                            .load(coverUrl)
                            .config(Bitmap.Config.RGB_565)
                            //.noFade()
                            .tag(picassoImgTag)
                            .into(hotItemCover);
                    hotItemCover.setTag(dataData);
                    titleText.setText(group.getTitle());
                    hotItemCover.setTag(group);
                }
            } catch (Exception e) {
                Log.d("ddddddddd", "LiveModel$Data$DataBean$GroupBean$LargeCoverBean: 有数据为空了");
                e.printStackTrace();
            }

        }
    }

    public class HeadViewHolder extends RecyclerView.ViewHolder {
        public HeadViewHolder(View itemView) {
            super(itemView);
        }
    }

    public class ProgressViewHolder extends SimplerViewHolder {
        public ProgressViewHolder(View itemView) {
            super(itemView);
        }

        @Override
        void bindView(LiveModel.Data.DataBean dataData) {
            ProgressBar progressBar = (ProgressBar) getChildView(R.id.live_hot_progress_bar);
            TextView textView = (TextView) getChildView(R.id.live_hot_progress_text);
            if (!mAccess2Net) {
                //没有网路的时候

            }
        }
    }

    private static class ProgressHandler extends Handler {

        private ViewPager mPager;

        public ProgressHandler(ViewPager pager) {
            mPager = pager;
        }

        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            if (what == 998) {
                int index = msg.arg1;
                mPager.setCurrentItem(index);
            }
        }
    }

}
